package com.richfit.barcodesystem_cczt.fragments.base;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.richfit.barcodesystem_cczt.R;
import com.richfit.barcodesystem_cczt.activitis.model.base.BaseBO;
import com.richfit.barcodesystem_cczt.activitis.model.main.IncrementalEntity;
import com.richfit.barcodesystem_cczt.activitis.model.users.UserInfo;
import com.richfit.barcodesystem_cczt.utils.constant.Global;
import com.richfit.barcodesystem_cczt.utils.sharedPreferences.DatabaseHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class BaseFragment extends Fragment {
    protected String mCompanyCode;
    protected String mModuleCode;
    protected String mBizType;
    protected String mRefType;
    protected int mFragmentType;
    /*该页签名称*/
    protected String mTabTitle;
    public BaseBO bo;
    public Gson gson = new Gson();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bo = DatabaseHelper.getBaseBO();
        Bundle bundle = getArguments();
        if (bundle != null) {
            mCompanyCode = bundle.getString(Global.EXTRA_COMPANY_CODE_KEY);
            mModuleCode = bundle.getString(Global.EXTRA_MODULE_CODE_KEY);
            mBizType = bundle.getString(Global.EXTRA_BIZ_TYPE_KEY);
            mRefType = bundle.getString(Global.EXTRA_REF_TYPE_KEY);
            mTabTitle = bundle.getString(Global.EXTRA_TITLE_KEY);
            mFragmentType = bundle.getInt(Global.EXTRA_FRAGMENT_TYPE_KEY);
        }
    }

    public void handleBarCodeScanResult(String type, String[] list) {

    }

    /**
     * 加载库存地点
     */
    protected void setIncremental(Spinner spinner) {
        //获取人员组织信息
        UserInfo userInfo = gson.fromJson(DatabaseHelper.getSp(bo.userinfo, ""), UserInfo.class);
        UserInfo.OrgBean orgBean = userInfo.getOrg();
        String orgCode = orgBean.getOrgCode();
        //获取库存地点信息
        List<String> stringList = new ArrayList<>();
        stringList.add("请选择");
        List<IncrementalEntity> incrementalEntities = gson.fromJson(DatabaseHelper.getSp(bo.incrementalInfoList, ""), new TypeToken<List<IncrementalEntity>>() {
        }.getType());
        List<IncrementalEntity> list = new ArrayList<>();
        for (IncrementalEntity incrementalEntity : incrementalEntities) {
            if (orgCode.equals(incrementalEntity.getOrgId())) {
                list.add(incrementalEntity);
                stringList.add(incrementalEntity.getName());

            }
        }
        //将数据添加到下拉框中
        ArrayAdapter adapter = new ArrayAdapter<>(this.getActivity(), R.layout.layout_spinner_item, stringList);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position != 0) {
                    //第一个位置为空,所以在list中，位置减一
                    IncrementalEntity incrementalEntity = list.get(position - 1);
                    spinner.setTag(incrementalEntity);
                } else {
                    //需要推送给详情页面空的库存地点
                    IncrementalEntity incrementalEntity = new IncrementalEntity();
                    spinner.setTag(incrementalEntity);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 调整分箱单的箱子到其他分箱单:下拉框加载，设置下拉框tag 为id
     *
     * @param spinner
     * @param stringList
     */
    protected void setSpinner(Spinner spinner, List<String> stringList, List<String> idList) {
        //将数据添加到下拉框中
        ArrayAdapter adapter = new ArrayAdapter<>(this.getActivity(), R.layout.layout_spinner_item, stringList);
        spinner.setAdapter(adapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                spinner.setTag(idList.get(position));
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    /**
     * 日期选择器
     *
     * @param dateType
     * @param textView
     * @return
     */
    protected TimePickerView setDate(int dateType, TextView textView) {
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        boolean[] type = new boolean[6];
        if (dateType == 0) {
            type = new boolean[]{true, true, true, false, false, false};
            dateFormat = "yyyy-MM-dd";
        } else if (dateType == 1) {
            type = new boolean[]{false, false, false, true, true, true};
            dateFormat = "HH:mm:ss";

        } else if (dateType == 2) {
            type = new boolean[]{true, true, true, true, true, true};
            dateFormat = "yyyy-MM-dd HH:mm:ss";
        }
        //时间选择器
        String finalDateFormat = dateFormat;
        TimePickerView pvTime = new TimePickerBuilder(this.getActivity(), (date, v12) -> textView.setText(getTimes(date, finalDateFormat)))
                .addOnCancelClickListener(v1 -> {
                    textView.setText("");
                })
                // 默认全部显示
                .setType(type)
                //取消按钮文字
                .setCancelText("重置")
                //确认按钮文字
                .setSubmitText("确定")
//                    .setContentSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
//                    .setTitleText("Title")//标题文字
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
//                    .setTitleColor(Color.BLACK)//标题文字颜色
//                    .setSubmitColor(Color.BLUE)//确定按钮文字颜色
//                    .setCancelColor(Color.BLUE)//取消按钮文字颜色
//                    .setTitleBgColor(0xFF666666)//标题背景颜色 Night mode
//                    .setBgColor(0xFF333333)//滚轮背景颜色 Night mode
//                    .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
//                    .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .build();
        return pvTime;
    }

    /**
     * 可根据需要自行格式化数据显示
     *
     * @param date
     * @param dateFormat
     * @return
     */
    protected String getTimes(Date date, String dateFormat) {
        SimpleDateFormat format = new SimpleDateFormat(dateFormat);
        return format.format(date);
    }

    /**
     * 记录最后的位置
     */
    private int lastX = 0;
    private int lastY = 0;

    /**
     * 控件拖动
     *
     * @param view
     */
    @SuppressLint("ClickableViewAccessibility")
    protected void setViewMove(View view) {
        view.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case (MotionEvent.ACTION_DOWN):
                    //按下按钮，记录开始移动标记
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int x = (int) (event.getRawX() - lastX);
                    int y = (int) (event.getRawY() - lastY);
                    int l = v.getLeft() + x;
                    int r = v.getRight() + x;
                    int t = v.getTop() + y;
                    int b = v.getBottom() + y;
                    v.layout(l, t, r, b);
                    lastX = (int) event.getRawX();
                    lastY = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_UP:
                    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-2, -2);
                    layoutParams.setMargins(v.getLeft(), v.getTop(), 0, 0);
                    view.setLayoutParams(layoutParams);
                    break;
                default:
                    break;
            }
            return false;
        });
    }

    protected Dialog setDialog(View rootView) {
        final Dialog dialog = new Dialog(this.getContext(), R.style.MaterialDialogSheet);
        dialog.setContentView(rootView);
        dialog.setCancelable(true);
        dialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.show();

        return dialog;
    }
}
